package com.idanchuang.component.just.web.base;

import com.alibaba.fastjson.JSONObject;
import com.idanchuang.component.base.exception.common.ErrorCode;
import com.idanchuang.component.base.exception.core.ExFactory;
import com.idanchuang.component.base.page.PageData;
import com.idanchuang.component.just.web.config.ComponentConfig;
import com.idanchuang.component.just.web.dto.LoginSsoUserDTO;
import com.idanchuang.component.just.web.dto.LoginUserDTO;
import com.idanchuang.component.just.web.util.IpUtils;
import com.idanchuang.component.just.web.util.RequestUtils;
import com.zoi7.component.core.base.BaseClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * Controller基类
 * @author yjy
 */
public class BaseController extends BaseClass {

    private static final Logger log = LoggerFactory.getLogger(BaseController.class);

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected ComponentConfig componentConfig;

    /**
     * 获取客户端信息
     *
     * @return 客户端信息
     */
    protected String getClientInfo() {
        return request.getHeader("User-Agent");
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    @Autowired(required = false)
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    @Autowired(required = false)
    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public ComponentConfig getComponentConfig() {
        return componentConfig;
    }

    @Autowired(required = false)
    public void setComponentConfig(ComponentConfig componentConfig) {
        this.componentConfig = componentConfig;
    }

    protected Object getFromSession(String key) {
        return request.getSession().getAttribute(key);
    }

    protected Object getFromSession(String key, Object defaultVal) {
        Object val = getFromSession(key);
        return val == null ? defaultVal : val;
    }

    protected void set2Session(String key, Serializable val) {
        request.getSession().setAttribute(key, val);
    }

    protected void removeFromSession(String key) {
        request.getSession().removeAttribute(key);
    }

    /**
     * @return 真实客户端ip
     */
    protected String getClientIp() {
        return IpUtils.getClientIp(request);
    }

    /**
     * @return 当前登入用户信息 (来源为gateway透传)
     */
    protected JSONObject getUserJsonObject() {
        return RequestUtils.getUserJsonObject(request);
    }

    /**
     * @return 当前登入用户信息 (来源为gateway透传)
     */
    protected LoginUserDTO getUserDTO() {
        return RequestUtils.getUserDTO(request);
    }

    /**
     * @return 当前登入用户信息 (来源为gateway透传)
     */
    protected String getUserJsonString() {
        return RequestUtils.getUserJsonString(request);
    }

    /**
     * @return 当前登入后台用户信息 (来源为gateway透传)
     */
    protected JSONObject getSsoUserJsonObject() {
        return RequestUtils.getSsoUserJsonObject(request);
    }

    /**
     * @return 当前登入后台用户信息 (来源为gateway透传)
     */
    protected LoginSsoUserDTO getSsoUserDTO() {
        return RequestUtils.getSsoUserDTO(request);
    }

    /**
     * @return 当前登入后台用户信息 (来源为gateway透传)
     */
    protected String getSsoUserJsonString() {
        return RequestUtils.getSsoUserJsonString(request);
    }

    /**
     * 检测非空
     *
     * @param params 参数
     */
    protected void checkNotNull(Object... params) {
        if (params != null && params.length > 0) {
            for (Object param : params) {
                if (param == null) {
                    throw ExFactory.throwCommon(ErrorCode.PARAM_ERROR, "参数提交不完整, 请检查");
                }
            }
        }
    }

    /**
     * 检测非空
     *
     * @param params 参数
     */
    protected void checkNotNullOrBlank(Object... params) {
        if (params != null && params.length > 0) {
            for (Object param : params) {
                if (param == null || isBlank(param.toString())) {
                    throw ExFactory.throwCommon(ErrorCode.PARAM_ERROR, "参数提交不完整, 请检查");
                }
            }
        }
    }

    /**
     * 检测参数验证结果
     *
     * @param bindingResult 验证结果
     */
    protected void checkBindResult(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.warn("checkBindResult : {}", bindingResult.getAllErrors());
            StringBuilder msg = new StringBuilder();
            for (ObjectError error : bindingResult.getAllErrors()) {
                msg.append(error.toString());
            }
            throw ExFactory.throwCommon(ErrorCode.PARAM_ERROR, msg);
        }
    }

    /**
     * 是否ajax请求
     *
     * @param request 请求
     * @return 是否
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(requestType);
    }

    /**
     * 自适应页号
     * @param pageNo 传参页号
     * @return 适应页号
     */
    protected static int adaptPageNo(Integer pageNo) {
        return PageData.adaptPageNo(pageNo);
    }

    /**
     * 自适应分页条数
     * @param limit 传参条数
     * @return 适应条数
     */
    protected static int adaptLimit(Integer limit) {
        return PageData.adaptLimit(limit);
    }

}
